package utils

import (
	"time"
	"net/http"
	"appengine"
	"appengine/datastore"
)

func ListReadme(r *http.Request, page int, limit int) []Readme {
	var rs []Readme
	offset := limit * (page -1)
	
	c := appengine.NewContext(r)
	
	q := datastore.NewQuery("Readme").Order("-Created").Limit(limit).Offset(offset)
	 
	_, err := q.GetAll(c, &rs)  
	
	if err != nil {
		panic(err.Error())
	}
	
	return rs

}

func GetAllReadme(r *http.Request) []Readme {
	var rs []Readme
	
	c := appengine.NewContext(r)
	
	q := datastore.NewQuery("Readme")
	 
	_, err := q.GetAll(c, &rs)  
	
	if err != nil {
		panic(err.Error())
	}
	
	return rs
}

func InsertReadme(readme Readme, r *http.Request) *datastore.Key {
	c := appengine.NewContext(r)
	
	key := datastore.NewKey(c, "Readme", readme.Name, 0 , nil)
	_,err := datastore.Put(c, key, &readme)
	
	if err != nil {
		panic(err.Error())
	} 
	
	return key
}

func GetReadme(name string, r *http.Request) (Readme, error) {
	c := appengine.NewContext(r)
	
	var readme Readme
	key := datastore.NewKey(c, "Readme", name, 0 , nil)
	
	if err := datastore.Get(c, key, &readme); err != nil {
		return Readme{}, err
	} 
	
	return readme, nil 
}


func DeleteReadme(name string, r *http.Request) {
	c := appengine.NewContext(r)
	key := datastore.NewKey(c, "Readme", name, 0, nil)
	
	if err := datastore.Delete(c, key); err != nil {
		panic(err.Error())
	}
} 

func GetGithubCount(r *http.Request) int64 {
	c := appengine.NewContext(r)
	
	var githubCount GithubCount
	key := datastore.NewKey(c, "GithubCount", "", 1 , nil)
	
	if err := datastore.Get(c, key, &githubCount); err != nil {
		githubCount = GithubCount {
			Id : 1,
			Count : 1,
		}
	}
	
	return githubCount.Count
}

func UpdateGithubCount(count int64, r *http.Request) {
	c := appengine.NewContext(r)
	
	var githubCount GithubCount
	key := datastore.NewKey(c, "GithubCount", "", 1 , nil)
	
	if err := datastore.Get(c, key, &githubCount); err != nil {
		githubCount = GithubCount {
			Id : 1,
			Count : 1,
		}
	}
	
	githubCount.Count = count
	
	_,err := datastore.Put(c, key, &githubCount)
	if err != nil {
		panic(err.Error())
	}
}

type Github struct {
	Id int64 `json: "id"`
	Name string `json: "name"`
	Html_url string `json: "html_url"`
	Description string `json: "description"`
	//Owner GithubOwner `json: "owner"`
}

type GithubOwner struct {
	Id int `json: "id"`
	Html_url string `json: "html_url"`
	Type string `json: "type"`
}

type GithubCollection struct {
	Pool []Github
}

type Readme struct {
	Id int64
	Name string
	Description string
	Content string `datastore:",noindex"`
	Created time.Time
	Source string
	Url string
}



type GithubCount struct {
	Id int64
	Count int64
}